package com.byinsight.web.actions.dimension;

import java.util.logging.Logger;

import com.byinsight.service.dto.Dimension;
import com.byinsight.web.actions.CheckSessionAction;
import com.byinsight.web.actions.util.DimensionDefinitionParser;
import com.byinsight.web.actions.util.DimensionHelper;

public class UpdateDimensionAction extends CheckSessionAction {
	private static final long serialVersionUID = -3161608826785585421L;
	private String dimdef;
	private static final Logger logger = Logger.getLogger(UpdateDimensionAction.class.getName());
	
	//keep this part simple. logic go to service and manager
	public String process() {
		logger.warning("begin UpdateDimensionAction");
		DimensionDefinitionParser parser = new DimensionDefinitionParser();
		parser.parse(dimdef);
		Dimension rootDim = parser.getRootDimension();
		logger.warning("begin call dimensionService.update");
		eg.backend.domain.Dimension root = dimensionService.updateDimension(rootDim);
		setChildrenParents(root);
		return DimensionHelper.toDimDefXml(DimensionHelper.toDto(root)).toString();
	}

	void setChildrenParents(eg.backend.domain.Dimension root) {
		logger.warning("children of " + root.getName() + ": ");
		for(eg.backend.domain.Dimension child : root.getChildren()) {
			logger.warning("child: " + child.getEncodedKey() + " - " + child.getName() + "- " + child.getParent());
			if(child.getParent() == null || child.getParent().indexOf("-") == 0) {
				logger.warning("set parent..");
				child.setParent(root.getEncodedKey());
				dimensionManager.save(child);
			}
			setChildrenParents(child);
		}
	}


	/* common */
	public void setDimdef(String dimdef) {
		this.dimdef = dimdef;
	}
	
}
